const gulp = require('gulp');
const GulpSSH = require('gulp-ssh');
const gulpUtil = require('gulp-util');

const src = [ // 上传哪些文件的到远程服务器
  '../pnpm-lock.yaml',
  '../.env.development',
  '../ecosystem.config.js',
  '../dist/**/*'
]

const config = {
  ssh: {
    host: '8.134.168.35',
    port: 22,
    username: 'root',
    password: '123456aA'
  },
  remotePath: '/usr/local/nestbacked_dev', // 上传到远程服务器的地址
  localFilesGlob: src,
};

const gulpSSH = new GulpSSH({
  ignoreErrors: false,
  sshConfig: config.ssh
});

// 上传文件任务
gulp.task('upload', () => {
  return gulp.src(config.localFilesGlob)
    .pipe(gulpSSH.dest(config.remotePath));
});

// 执行远程命令任务来安装依赖
gulp.task('install-dependencies', () => {
  return gulpSSH
    .shell([`cd ${config.remotePath}`, 'pnpm install'])
    .on('ssh2Data', (data) => {
      gulpUtil.log(data.toString());
    });
});

gulp.task('restart-pm2', () => {
  return gulpSSH
    .shell([`cd ${config.remotePath}`, 'pm2 restart ./ecosystem.config.js'])
    .on('ssh2Data', (data) => {
      gulpUtil.log(data.toString());
    });
});

// 默认任务
gulp.task('default', gulp.series('upload', 'install-dependencies', 'restart-pm2', (done) => {
  gulpUtil.log('Files have been uploaded successfully!');
  done();
}));
